<?php

namespace app\controller;

use support\Request;
use think\facade\Db;
use GatewayWorker\Lib\Gateway;
use support\Cache;
use app\process\MqttClient;
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Protocols\Http\Response;
use Workerman\Timer;
use Workerman\Protocols\Http\Chunk;

class IndexController
{
    //不需要登录的接口
    protected $noNeedLogin = ['login','index'];
    protected $hardware_id = 10;

    public function index(Request $request)
    {
        $url = 'http://edapi.xzshangxin.com/index/index';
        $opt = 'a=1&timestamp='.time();
        $method = 'DES-ECB';
        $passwd = '123123';//用户的密钥
        $sign = openssl_encrypt($opt, $method, $passwd,OPENSSL_RAW_DATA,'');
        $data['sign'] = $sign;
        $a = $this->PostJson($url,$data);
        return json($a);
        // echo 1;
        // 创建一个TCP Worker
//     $tcpWorker = new Worker('tcp://0.0.0.0:8282');

//     // 存储接收到的TCP消息
//     $receivedData = null;

//     // TCP连接处理
//     $tcpWorker->onMessage = function (TcpConnection $connection, $data) use (&$receivedData) {
//         // 处理接收到的数据
//         $receivedData = 121; // 假设数据是JSON格式
//     };

//     // 启动TCP Worker
//     Worker::runAll();

// // HTTP路由
// return function (Request $request, Response $response) use (&$receivedData) {
//     // 获取前端请求数据
//     $requestData = $request->post(); // 或者 $request->get() 根据需要

//     // 创建TCP连接
//     $client = new \Workerman\Connection\AsyncTcpConnection('tcp://127.0.0.1:8282');

//     // 发送请求到TCP服务器
//     $client->send('123'); // 将前端请求数据发送到TCP服务器

//     // 处理TCP响应
//     $client->onMessage = function ($connection, $data) use ($response) {
//         echo 1;
//         // 返回HTTP JSON响应
//         $response->json(['code'=>1,'data'=>'123']); // 将TCP响应转换为JSON并返回
//     };

//     $client->onError = function ($connection, $code, $msg) use ($response) {
//         // 处理错误
//         $response->json(['status' => 'error', 'message' => $msg], 500);
//     };

//     $client->onClose = function ($connection) {
//         // 处理连接关闭
//     };

//     // 连接到TCP服务器
//     $client->connect();
// };

        // return 12;
        // Gateway::$registerAddress="127.0.0.1:1237";
        // Gateway::sendToUid(1,2);
        // $Gateway = new Gateway("tcp://0.0.0.0:8282");
        // $Gateway->registerAddress = '127.0.0.1:1237';
        // $Gateway->sendToUid(1,2);
        // $mqtt = new \Workerman\Mqtt\Client('mqtt://mqtt.tinycool.cn:1883', array(
        //     'debug' => true,
        //     "username"=>"admin", "password"=>"wxk668899"
        // ));
        // $mqtt->onConnect = function($mqtt) {
        //     $data['cmd'] = 'CtlSw';
        //     $data['targetDevice'] = 'CtlSw';
        //     $data['sourceDevice'] = 'CtlSw';
        //     $data['data'] = ['SwIndex'=>1,'SwCtl'=>0];
        //     $str = json_encode($data,320);
        //     $mqtt->publish('wxk/publish', $str);//向主题发送内容
        //     $mqtt->close();   
        // };
        // $mqtt->connect(); 
        // $http_worker = new Worker('http://127.0.0.1:8787');   
        // echo 2;
        // $http_worker->onMessage = function($con, $data){
        //     echo 1;
        // };
            // $http_connection = $request->connection;
            // // $http_connection->send(1);
            // $inner_tcp_client = new AsyncTcpConnection('tcp://127.0.0.1:8282'); 

            // $inner_tcp_client->onConnect = function( $inner_tcp_client)
            // {     

            //     $reg_info = "{'from':1,'to':2,'data':111}";
            //     $inner_tcp_client->send($reg_info);
            // };

            // $inner_tcp_client->onMessage = function( $inner_tcp_client, $data) use ($http_connection) { 
            //     $inner_tcp_client->close();
            //     $http_connection->send(new Chunk($data));
            //     $http_connection->send(new Chunk('')); // 发送空的的chunk代表response结束
            //     // $http_connection->send('123');
            // };

            // $inner_tcp_client->connect();
            // return response()->withHeaders([
            //     "Transfer-Encoding" => "chunked",
            //     "Content-Type"=>"application/json"
            // ]);
    }
    public function PostJson($url, $data = NULL,$headers="")
    {
        $curl = curl_init();
        $header =array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen(json_encode($data)),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        );
        if($headers){
            $header[]=$headers;
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            return 'data is null';
        }
        if (is_array($data)) {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 60); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return json_decode($res,true);
    }
    public function login(Request $request)
    {
        $request->session()->set('user', );
        return json(['code' => 0, 'msg' => 'login ok']);
    }

    public function info()
    {
        return json(['code' => 0, 'msg' => 'ok', 'data' => session('user')]);
    }

}
